import headerStyle from "@/styles/header.module.scss";
import CookieCutter from "cookie-cutter";
import { useEffect, useState } from "react";
import LottieView from "./LottieView";
import AvatarLottieJson from "@/public/lottie/avatar.json";
import { Dropdown } from "antd";
import type { MenuProps } from "antd";
import { useRouter } from "next/router";
interface Props {
  children: React.ReactNode;
}
interface User {
  name: string;
  id: string;
  account: string;
}

const items: MenuProps["items"] = [
  {
    key: "write",
    label: "写文章",
  },
  {
    key: "logout",
    label: "退出",
  },
];

const MainLayout = (props: Props) => {
  const [user, setUser] = useState<User>({ name: "", id: "", account: "" });
  const router = useRouter();

  useEffect(() => {
    const user = CookieCutter.get("user");
    if (user) {
      setUser(JSON.parse(decodeURIComponent(user)));
    }
  }, []);

  const onMenuClick: MenuProps["onClick"] = ({ key }) => {
    if ("write" === key) {
      router.push("/write");
    }
    if ("logout" === key) {
      CookieCutter.set("Authorization", "", { expires: new Date() });
      CookieCutter.set("user", "", { expires: new Date() });
      router.replace("/login");
    }
  };

  return (
    <div>
      <header className={headerStyle.header}>
        <span></span>
        <Dropdown menu={{ items, onClick: onMenuClick }}>
          <div className="flex items-center cursor-pointer">
            <LottieView
              animationData={AvatarLottieJson}
              loop={true}
              width={"36px"}
              height={"36px"}
            ></LottieView>
            <span className="ml-1 text-slate-500">{user.name}</span>
          </div>
        </Dropdown>
      </header>
      <div>{props.children}</div>
    </div>
  );
};

export default MainLayout;
